<?php
namespace app\common\model\Tag;

use support\bootstrap\Cache;
use support\Db;
use support\Model;
use think\model\concern\SoftDelete;

/**
 * 商品标签关联模型
 * Class GoodsTagRelationCommonModel
 * @package app\common\model\Tag
 */
class GoodsTagRelationCommonModel extends Model
{

    use SoftDelete;

    // 表名
    protected $name = 'goods_tag_relation';

    protected $deleteTime = 'deletetime';

    /**
     * 获取商品的标签
     * @param int $goodsId 商品id
     * @return array
     */
    public function getTagIdsByGoodsId(int $goodsId) :array
    {
        if(empty($goodsId)){
            return [];
        }
        $tagIds = $this->getGoodsTagIdsCache($goodsId);
        if(empty($tagIds)){
            $tagIds = $this->where(['goods_id' => $goodsId])->column('tag_id');
            $this->setGoodsTagIdsCache($tagIds , $goodsId);
        }
        return $tagIds;
    }


    /**
     * 获取缓存
     * @param int $goodsId
     * @return mixed
     */
    public function getGoodsTagIdsCache(int $goodsId )
    {
        return Cache::get( $this->getCacheKey($goodsId) , [] );
    }

    /**
     * 设置缓存
     * @param mixed $value
     * @param int $goodsId
     * @param int $expire
     */
    public function setGoodsTagIdsCache($value , int $goodsId , int $expire = 72000)
    {
        Cache::set( $this->getCacheKey($goodsId) , $value , $expire);
    }


    /**
     * 删除缓存
     * @param int $goodsId
     */
    public function delGoodsTagIdsCache(int $goodsId )
    {
        Cache::delete( $this->getCacheKey($goodsId));
    }


    /**
     * 获取缓存key
     * @param int $goodsId
     * @return string
     */
    protected function getCacheKey(int $goodsId)
    {
        return 'goodsTagIds-' . $goodsId;
    }



}